<template>
  <div class="container">
    <view-box ref="viewBox" body-padding-top="46px">
      <x-header class="my-header" >编辑健康档案</x-header>
      <div class="service_item" :class="isHide">
        <group>
          <x-input disabled title="姓名  " v-model="realName"></x-input>

          <x-input title="电话  " v-model="form.tel" :max="13" is-type="china-mobile"></x-input>
          <x-textarea :title="$t('地址  ')" v-model="form.address2Show" placeholder="请通过地图获取" :show-counter="false" :max="200" :height="50" :rows="3" :cols="30"></x-textarea>
          <x-input title="" disabled="true" >
            <x-button slot="right" type="primary" :gradients="['#1D62F0', '#19D5FD']" mini @click.native="openMap()">打开地图</x-button>
          </x-input>
        </group>
      </div>
      <group>
        <x-button :gradients="['#1D62F0', '#19D5FD']" :class="isHide" @click.native="save()">保存</x-button>
      </group>
      <div class="amap-page-container" :class="hideMap">
        <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult" style="width: 300px;"></el-amap-search-box>
        <el-amap vid="amap" :zoom="zoom" :amap-manager="amapManager" :plugin="plugin" class="amap-demo" :center="center" :events="events">
          <el-amap-marker :position="center" ></el-amap-marker>
        </el-amap>
        <div style="font-size: 15px;color: gray" :class="hideMap">
          {{address}}
        </div>
        <x-button slot="right" type="primary" :gradients="['#1D62F0', '#19D5FD']" mini @click.native="ensure()">确定</x-button>
        <x-button slot="right" type="default" mini @click.native="cancel()">取消</x-button>
      </div>
    </view-box>
    <toast v-model="finishForm" type="text" :time="2000" is-show-mask text="请完善信息" position="bottom"></toast>
    <toast v-model="finished" type="text" :time="1500" is-show-mask text="保存成功" position="bottom"></toast>
    <toast v-model="falseForm" type="text" :time="1500" is-show-mask text="请填写正确的信息" position="bottom"></toast>
  </div>
</template>

<script>
  import {  Toast,XTextarea,XInput,Selector, XButton,ViewBox,XHeader,Flexbox, FlexboxItem, Group, Cell  } from 'vux'
  import VueAMap from 'vue-amap'
  let amapManager = new VueAMap.AMapManager();
  export default {
    data(){
      let self = this;
      return {
        relations:'',     //关系列表
        isHide:'',        //列表隐藏
        hideMap:'hidemap',   //地图隐藏
        areas:'',           //所有地区列表
        finishForm:false,     //是否完成列表
        finished:false,        //保存是否成功
        falseForm:false,        //填写信息失败
        realName:'',          //患者姓名
        patientData:'',       //原患者信息
        form:{              //上传的data
          tel:'',
          provinceId:'',
          cityId:'',
          countyId:'',
          address2Show:'',
          lng:'',
          lat:''
        },
        zoom: 12,           //地图大小
        center: [103.93414, 30.7542],         //地图默认中心
        amapManager: amapManager,
        lng: 0,                   //经度
        lat: 0,                   //纬度
        address: '',               //具体地址
        loaded: false,
        searchOption: {
          city: '成都',
          citylimit: false
        },
        mapCenter: [103.93414, 30.7542],
        plugin: [{
          pName: 'Geolocation',
          events: {
            init(o) {        //地图初始化获取的地位地址
              // o 是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  self.lng = result.position.lng;
                  self.lat = result.position.lat;
                  self.center = [self.lng, self.lat];
                  self.loaded = true;
                  self.$nextTick();
                }
                let geocoder = new AMap.Geocoder({
                  radius: 1000,
                  extensions: "all"
                });
                geocoder.getAddress([self.lng, self.lat], function (status, result) {
                  if (status === 'complete' && result.info === 'OK') {
                    if (result && result.regeocode) {
                      self.address = result.regeocode.formattedAddress;
                      self.$nextTick();
                    }
                  }
                });
              });
            },

          },
        }]
      }
    },
    mounted(){
      this.patientData=this.$route.query
      let patientData=this.patientData
      this.realName=patientData.realName
      this.form.tel=patientData.tel
      this.form.provinceId=patientData.provinceId
      this.form.cityId=patientData.cityId
      this.form.countyId=patientData.countyId
      this.form.address2Show=patientData.address2Show
      this.form.lng=patientData.lng
      this.form.lat=patientData.lat
      console.log(patientData)
      this.getAreas()
    },
    methods:{
      onSearchResult(pois) {     //搜索后获取地址
        let latSum = 0;
        let lngSum = 0;
        if (pois.length > 0) {
          pois.forEach(poi => {
            let {lng, lat} = poi;
            lngSum += lng;
            latSum += lat;
          });
          this.lng=lngSum / pois.length
          this.lat=latSum / pois.length
          this.center = [this.lng, this.lat];
        }
        let self=this
        let geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: "all"
        });
        geocoder.getAddress(this.center, function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            if (result && result.regeocode) {
              self.address = result.regeocode.formattedAddress;
              self.$nextTick();
            }
          }
        });
        console.log(this.center);
        console.log(this.address)
      },
      openMap(){
        this.isHide="hide"
        this.hideMap=""
      },
      getAreas(){
        this.Ajax('get','/javaapi/areas',{},(res)=>{
          this.areas=res
        })
      },
      ensure(){
        //确定地址
        this.isHide='';
        this.hideMap='hidemap'
        this.form.lng=this.lng;
        this.form.lat=this.lat;
        this.form.address2Show=this.address
        //确定省市区id
        let address=this.address,pro,city,county,xian,shi
        console.log(address)
        pro=address.split('省')
        city=pro[1].split('市')
        county=city[1].split('区')
        xian=city[1].split('县')
        shi=city[1].split('市')
        let areas=this.areas
        areas.childrenAreaList.forEach((item)=>{   //获取省级id
          if (pro[0]==item.name){
            this.form.provinceId=item.id
          }
        })
        areas.childrenArea[pro[0]].childrenAreaList.forEach((item)=>{    //获取市级id
          if(city[0]+'市'==item.name){
            this.form.cityId=item.id
          }
        })
        city=city[0]+'市'
        areas.childrenArea[pro[0]].childrenArea[city].childrenAreaList.forEach((item)=>{   //获得区县id
          if(county[0]+'区'==item.name||xian[0]+'县'==item.name||shi[0]+'市'==item.name){
            this.form.countyId=item.id
          }
        })
      },
      cancel(){
        //取消定址
        this.isHide='';
        this.hideMap='hidemap'
      },
      save(){       //保存病患信息
        let form=this.form;
        if(form.tel&&form.address2Show){
          this.Ajax('put','/javaapi/patient/'+this.patientData.pid,form,(res)=>{
            console.log(res)
            if(res.body.body=='success'){
              this.finished=true
              setTimeout(()=>{
                this.$router.go(-1)
              },1500)
            }else if(res=='110'){
              this.falseForm=true
            }
          })
        }else{
          this.finishForm=true
        }
      }
    },
    components: {
      Toast,XTextarea,XInput, Selector,XButton,ViewBox,XHeader,Flexbox, FlexboxItem, Group, Cell
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped  lang="stylus" rel="stylesheet/stylus">
  .hide{
    display none
  }
  .hidemap{
    display none
  }
  .amap-demo {
    height: 90%;
  }

  .search-box {
    position: absolute;
    top: 25px;
    left: 20px;
  }

  .amap-page-container {
    position: relative;
    height 95%
  }
  .flex-demo{
    min-height: 70px;
    background-color: white;
  }
  .content{
    padding: 1px 10px 1px 10px;
  }
  .content p{
    margin: 15px 0 15px 0;
  }
  .my-header {
    background-color: rgb(255, 104, 140);
    position: fixed;
    height: 46px;
    left: 0;
    top: 0;
    width: 100%;
    z-index: 100;
  }
  .icon
    display:inline-block;
    float left
    margin:10px 5px 15px 20px;
    width:50px;
    height:50px;
    background-size:45px 45px;
    background-repeat:no-repeat;
    &.visit_1
      background-image url('../mainpage/icons/visit_1.png')
    &.visit_2
      background-image url('../mainpage/icons/visit_2.png')
    &.visit_3
      background-image url('../mainpage/icons/visit_3.png')
    &.visit_4
      background-image url('../mainpage/icons/visit_4.png')
    &.visit_5
      background-image url('../mainpage/icons/visit_5.png')
    &.visit_6
      background-image url('../mainpage/icons/visit_6.png')
  .item_title
    display inline-block
    margin 10px 0 5px 0
    color black
    font-weight bold
  .item_des
    color gray
    font-size 12px
</style>
